package com.water.camera.adapter;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.water.camera.R;
import com.water.camera.bean.EditItem;
import com.water.camera.databinding.EditItemBinding;
import com.water.camera.it.EditListener;

import java.util.List;

public class EditListAdapter extends RecyclerView.Adapter {
    List<EditItem> list;
    EditListener listener;

    public EditListAdapter(List<EditItem> list, EditListener listener) {
        this.list = list;
        this.listener = listener;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        EditItemBinding binding = EditItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class Holder extends RecyclerView.ViewHolder {
        EditItemBinding binding;

        public Holder(EditItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        private void bind(int i) {
            EditItem item = list.get(i);
            binding.title.setText(item.name);
            if (item.show) {
                binding.title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_edit_switch_on, 0, 0, 0);
            } else {
                binding.title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_edit_switch_off, 0, 0, 0);
            }
            if (TextUtils.isEmpty(item.value)) {
                binding.desc.setText("点击编辑");
            } else {
                binding.desc.setText(item.value);
            }
            binding.title.setOnClickListener(v -> {
                item.show = !item.show;
                if (item.show) {
                    binding.title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_edit_switch_on, 0, 0, 0);
                } else {
                    binding.title.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_edit_switch_off, 0, 0, 0);
                }
                item.updateShow(item.show);
                listener.onShowChange(item);
            });
            binding.desc.setOnClickListener(v -> {
                listener.toEdit(item, getBindingAdapterPosition());
            });
        }
    }

    public void append(EditItem item) {
        int p = list.size() - 1;
        list.add(p, item);
        notifyItemInserted(p);
    }

    public void remove(int p) {
        list.remove(p);
        notifyItemRemoved(p);
    }
}
